#!/usr/bin/perl
# Haifa University WiFi - stay online
# HTTP version
# Author: Ofir Cohen


# Dependencies
use Modern::Perl;
use LWP::UserAgent;
use HTTP::Request::Common qw(POST);
use XML::Twig;


# variables definition
my ($file,$twig,$root,$ua,$reqstr,$request,$content);
my ($user,$pass,$aclass,$url,$str,$interval,$debug,$dfile);
$file = "settings.xml";


# read settings
die("Error: settings file doesn't exist!") unless (-e $file);
$twig = XML::Twig->new;
$twig->parsefile($file);
$root = $twig->root;
$user = $root->first_child_text('user');
$pass = $root->first_child_text('pass');
$aclass = $root->first_child_text('aclass');
$url = $root->first_child_text('url');
$str = $root->first_child_text('str');
$interval = $root->first_child_text('interval');
$debug = $root->first_child_text('debug');
$dfile = $root->first_child_text('dfile');
undef $twig;
undef $root;


# debug ?
if ($debug)
{
	if (!open(FILE, ">>$dfile")) {
		warn $!;
		$debug=0;
	}
}


# prepare connection string
$ua = LWP::UserAgent->new; 
$ua->agent("Mozilla 8.0 blah...");
$reqstr = (POST $url, 
["user" => $user, 
"pass" => $pass]);


# keep-alive thread - sends signal every INTERVAL secs
for ( ; ; sleep($interval))
{
	# do not send request if no ip is assigned (yet)
	next unless (getip());

	# send request
	$request = $ua->request($reqstr);
	
	if ($request->is_success)
	{
		$content = $request->content; 
		if ($content =~ m/$str/) {
			print "success";
			WriteToDebug("success.") if $debug;
		} else {
			WriteToDebug("wrong username/password.") if $debug;
		}
	}
}


# close file handle for debugging
(close(FILE) || die("Unable to close $dfile for debugging")) if ($debug);


# clean exit
exit;


# getip()
# -------
# finds if user has established Wi-Fi connection already
# returns: 1 --> valid ip is set
#		   0 --> not connected to WiFi            


sub getip {
	local $_ = `ipconfig`;
	return (/(?<ipaddr>$aclass\.\d{0,3}\.\d{0,3}\.\d{0,3})/);
}


# Write data to debug file
sub WriteToDebug { 
	my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
	printf( FILE "(%4d-%02d-%02d) (%02d:%02d:%02d) @_\n", $year+1900,$mon+1,$mday,$hour,$min,$sec);
}

